// pages/confirmorder/confirmorder.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    ID: false,
    addr: {
      name: '',
      phone: '',
      addr: ''
    },
    items: [
      { name: 'waimai', value: '外卖', id: '2' },
      { name: 'ziqu', value: '自取', id: '3' },
    ],
    types: [
      { id: '1', img: "/images/weixin.png", typeName: "微信支付", checked: "true" },
      { id: "2", img: "/images/xxzf.png", typeName: "余额支付", }
    ],
    foods: {},
    tableid: '',
    cart: [],
    food: [],
    znum: 0,
    zprice: 0,
    preafterprice: 0,
    leveMoney: 0,
    checked1: false,
    pstype: '1',
    textareavalue: '',
    phonevalue: '',
    coupon: {},
    // collage: '',
    collage_goods: [],
    points: {},
    integral: 0,
    integralpri: 0,
    yhq: {
      id: null,
      name: '不使用优惠券',
      pri: 0
    },
    orderdd: {},//提交的时候的订单
    bool: false,
  },
  radioChange: function (e) {
    this.setData({
      pstype: e.detail.value
    })
  },

  textareachange: function (e) {
    this.setData({
      textareavalue: e.detail.value
    })
  },
  phonevalue: function (e) {
    this.setData({
      phonevalue: e.detail.value
    })
  },
  //填写地址:  发起通讯录
  addr: function (e) {
    var that = this;
    wx.chooseAddress({
      success: function (res) {
       // console.log('获取地址成功');
        that.setData({
          'addr.name': res.userName,
          'addr.phone': res.telNumber,
          'addr.addr': res.provinceName + res.cityName + res.countyName + res.detailInfo,
        })
      },
      fail: function (res) {
        //console.log('获取地址失败');
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.address']) {
              wx.authorize({
                scope: 'scope.address',
                success(res) {
                },
                fail: function (res) {
                  wx.openSetting({
                    success: (res) => {
                      if (!res.authSetting["scope.address"]) {
                        wx.showModal({
                          title: '提示',
                          content: '通讯地址授权失败，不能使用外卖',
                          showCancel: false,
                          success: function (res) {
                            if (res.confirm) {
                              that.setData({
                                pstype: 1
                              })
                            }
                          }
                        })
                      }
                    }
                  })
                }
              })
            }
          }
        })
      }
    })
  },

  /*总的价格数量 */
  znumprice: function () {
    var znum = 0;
    var zprice = 0;
    if (this.data.ID == false) {
      this.data.cart.forEach(function (item, index) {
        znum += item.num
        zprice += item.price * item.num
      })
      if (znum > 99) {
        znum = '99+'
      }
      this.setData({
        znum: znum,
        zprice: zprice,
      })
    }

  },
  /* 选择优惠券*/
  chooseyh: function (e) {
    var that = this;
    if (that)
      if (that.data.coupon.data.length == 0) {
        wx.showToast({
          title: '您暂无可使用的优惠券',
          icon: 'none',
          duration: 2000
        })
        return false;
      } else {
        wx.navigateTo({
          url: '../myYouhui/myYouhui?id=0',
        })
      }
  },
  /*优惠后的价格*/
  preafterprice: function () {
    var that = this;
    var order = {};
    var food = [];
    // var points=null;
    var yhqid = null;
    if (that.data.ID == false) {
      that.data.cart.forEach(function (item) {
        var spec = '';
        // console.log("000", that.data.cart)
        // console.log("111", item)
        food.push({ food_id: item.goodid, spec_item: spec, count: item.num })
      })
    } else {
      // console.log('ID', that.data.ID)
      // var foods = that.data.collage_goods;
      var foods = that.data.foods;
      // console.log("foods", foods)
      food.push({ food_id: foods.goods_id, count: 1 })
    }

    if (parseInt(that.data.yhq.id)) {
      order = {
        price: that.data.zprice,
        true_price: that.data.preafterprice,
        coupon_id: parseInt(that.data.yhq.id),
        note: that.data.textareavalue,
        phone: that.data.addr.phone,
        food: food,
        type: parseInt(that.data.pstype),
        address: that.data.addr.addr,
        name: that.data.addr.name,
      }
    } else {
      order = {
        price: that.data.zprice,
        true_price: that.data.preafterprice,
        note: that.data.textareavalue,
        phone: that.data.addr.phone,
        food: food,
        type: parseInt(that.data.pstype),
        address: that.data.addr.addr,
        name: that.data.addr.name,
      }
    }

    // if (that.data.colllage != '') {
    //   order.collage = that.data.collage;
    // }

    that.setData({
      orderdd: order
    })
     //console.log("***", order)
    var type = order.type
    wx.request({
      url: app.globalData.directory + 'api/v2/pay/handle_price/' + type,
      method: 'POST',
      data: order,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        // console.log("折扣后res", res)
        if (res.data.status == 'ok') {
          that.setData({
            preafterprice: res.data.data,
            'orderdd.true_price': res.data.data
          })

          // }else{
          //   that.setData({
          //     preafterprice: that.data.foods.collage_price,
          //     'orderdd.true_price': that.data.foods.collage_price
          //   })
          // }
          if (that.data.bool) {
            // console.log("orderdd", that.data.orderdd)
            that.pay();
          }
        } else {
          // console.log(res,1215475754);
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000,
          })
        }
      }
    })
  },
  /*支付 */
  pay: function () {
    var that = this;
    var preafterprice = that.data.preafterprice;
    var leveMoney = that.data.leveMoney;
    var pstype = that.data.pstype
    // console.log("pays", pstype)
    var cart2 = wx.getStorageSync('cart1');
    wx.setStorageSync('shopcar', cart2);
    wx.request({
      url: app.globalData.directory + 'api/v2/pay/order_pay',
      method: 'POST',
      data: that.data.orderdd,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        // console.log("pay", res.data)
        if (pstype == "1") {
          if (res.data.status == 'ok') {
            if (res.data.msg == 'success') {
              // 发起支付
              wx.requestPayment({
                'timeStamp': res.data.data.timestamp,
                'nonceStr': res.data.data.nonceStr,
                'package': res.data.data.package,
                'signType': res.data.data.signType,
                'paySign': res.data.data.paySign,
                'success': function (res) {
                  setTimeout(function () {
                    wx.navigateTo({
                      url: '../dingdan/dingdan?id=2',
                    })
                  }, 1000)
                },
                'fail': function (res) {
                 // console.log(res)
                  wx.showToast({
                    title: res.errMsg,
                    icon: 'none',
                    duration: 2000,
                  })
                  setTimeout(function () {
                    wx.navigateTo({
                      url: '../dingdan/dingdan?id=1',
                    })
                  }, 1000)
                }
              })
            }
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000,
            })

          }
        } else {
          // console.log(res.data.status,"******")
          if (res.data.status == "ok") {
            if (res.data.msg == "success") {
              wx.request({
                url: app.globalData.directory + 'api/v2/user/getuser',
                method: "POST",
                data: that.data.orderdd,
                header: {
                  'content-type': 'application/json',
                  'token': wx.getStorageSync('token')
                },
                success: function (res) {
                  // console.log(res.data.status,89898989)
                  if (res.data.status == "ok") {
                    wx.showToast({
                      title: '支付成功',
                      icon: 'success',
                      duration: 1000,
                    })
                    setTimeout(function () {
                      wx.navigateTo({
                        url: '../dingdan/dingdan?id=2',
                      })
                    }, 1000)
                  }
                }
              })
            }
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000,
            })
            wx.showModal({
              title: '提示',
              content: '余额不足，是否去充值',
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../toRecharge/toRecharge',
                  })
                } else {
                  setTimeout(function () {
                    wx.navigateTo({
                      url: '../dingdan/dingdan?id=1',
                    })
                  }, 1000)
                }
              }
            })
          }




        }
      }

    })
  },
  /*提交表单 */
  bindsub: function () {
    this.setData({
      bool: true
    })
    this.preafterprice();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (option) {
    if (option.id !== "undefined") {
      this.setData({
        cart: wx.getStorageSync('cart'),
        coupon: app.globalData.coupon,
        ID: true
      })
      var that = this
      wx.request({
        url: app.globalData.directory + 'api/v2/getCollageDetails/' + option.id,
        header: {
          'content-type': 'application/json', // 默认值
          'token': wx.getStorageSync('token')
        },
        success: function (res) {
          if (res.data.status == "ok") {
            var foods = that.data.foods;
            foods = res.data.data;
            // that.data.collage = res.data.data.id;
            // console.log(foods,222112)
            that.setData({
              foods: foods
            })
            // that.data.foods = res.data.data.collage_goods;
          } else {
            wx.showToast({
              title: '请求失败,请重试',
              icon: 'none',
              duration: 2000,
            })
          }
        }
      })
      if (parseInt(app.globalData.choosewelfare) == 0) {
        that.setData({
          'yhq.id': null,
          'yhq.name': '不使用优惠券',
          'yhq.pri': 0,
        })
        that.znumprice();
        // that.integral();
        // that.preafterprice();
        return false;
      }
      if (parseInt(app.globalData.choosewelfare)) {
        that.data.coupon.data.forEach(function (item, index) {
          if (item.id == app.globalData.choosewelfare) {
            that.setData({
              'yhq.id': item.id,
              'yhq.name': item.name,
              'yhq.pri': item.amount_cash,
            })
          }
        })
      }
      this.znumprice();

    } else {
      var that = this;
      this.setData({
        cart: wx.getStorageSync('cart'),
        coupon: app.globalData.coupon,
        leveMoney: app.globalData.leavMoney,
        ID: false
      })
      wx.request({
        url: app.globalData.directory + 'api/v2/getGoodsAll',
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        success: function (res) {
          if (res.data.status == 'ok') {
            that.setData({
              foods: res.data.data
            })
          } else {
            wx.showToast({
              title: '请求失败,请重试',
              icon: 'none',
              duration: 2000,
            })
          }
        }
      })

      if (parseInt(app.globalData.choosewelfare) == 0) {
        that.setData({
          'yhq.id': null,
          'yhq.name': '不使用优惠券',
          'yhq.pri': 0,
        })
        that.znumprice();
        // that.integral();
        // that.preafterprice();
        return false;
      }
      if (parseInt(app.globalData.choosewelfare)) {
        that.data.coupon.data.forEach(function (item, index) {
          if (item.id == app.globalData.choosewelfare) {
            that.setData({
              'yhq.id': item.id,
              'yhq.name': item.name,
              'yhq.pri': item.amount_cash,
            })
          }
        })
      }
    }
    this.znumprice();
    // this.integral();
    // this.preafterprice();


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (parseInt(app.globalData.choosewelfare) == 0) {
      that.setData({
        'yhq.id': null,
        'yhq.name': '不使用优惠券',
        'yhq.pri': 0,
      })
      // that.preafterprice();
      return false;
    }
    if (parseInt(app.globalData.choosewelfare)) {
      that.data.coupon.data.forEach(function (item, index) {
        if (item.id == app.globalData.choosewelfare) {
          that.setData({
            'yhq.id': item.id,
            'yhq.name': item.name,
            'yhq.pri': item.amount_cash,
          })
          // that.preafterprice();
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})